#pragma once

#include <iostream>
#include <string>
#include "Log.hpp"
#include "Init.hpp"

using namespace std;

extern Log log;
Init init;

class Task
{
public:
    Task(int sockfd, const std::string &clientip, const uint16_t clientport)
        : _sockfd(sockfd)
        , _clientip(clientip)
        , _clientport(clientport)
    {}

    void run()
    {
        char buffer[4096];
        ssize_t n = read(_sockfd, buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            cout << "client key# " << buffer << endl;
            std::string echo_string = init.translation(buffer);

            write(_sockfd, echo_string.c_str(), echo_string.size());
        }
        else if (n == 0)
        {
            log(Info, "%s:%d quit, server close sockfd: %d", _clientip.c_str(), _clientport, _sockfd);
        }
        else
        {
            log(Warning, "read error, sockfd: %d, client ip: %s, client port: %d", 
                _sockfd, _clientip.c_str(), _clientport);
        }    
    }

    void operator()()
    {
        run();
    }

    ~Task()
    {}

private:
    int _sockfd;
    string _clientip;
    uint16_t _clientport;
};